import {
  dsx
} from './datax';
import {
  dateTool
} from '~/tools/date'
import {
  ds
} from './data'
import {
  ui
} from '~/tools/ui'

export const coupon = {
  updateCoupon(coupon, obtainNum) { // 减少优惠券存量（有数量限制的）
    if (!(coupon.left * 1 > 0)) return

    ds.cloudUpdate('coupons', coupon._id, {
      left: coupon.left * 1 - obtainNum * 1
    }, res => {
      // console.log(res)
    })
  },
  async updateUserLimit(coupon, user) { // 增加用户领用量（有领用限制的）
    if (!coupon.limit) return

    const couponRecord = user.couponRecord || {}
    couponRecord[coupon._id] = couponRecord[coupon._id] || {
      num: 0
    }
    couponRecord[coupon._id].num = couponRecord[coupon._id].num * 1 + 1
    await new Promise(resolve => {
      ds.cloudUpdate('users', user._id, {
        couponRecord
      }, res => {
        resolve()
      })
    })
  },
  async updateUserOpenGId(coupon, user) { // 标记用户已经领过群专属券
    if (!coupon.openGId) return

    const couponRecord = user.couponRecord || {}
    couponRecord[coupon._id] = couponRecord[coupon._id] || {
      num: 0
    }
    couponRecord[coupon._id].openGId = coupon.openGId
    await new Promise(resolve => {
      ds.cloudUpdate('users', user._id, {
        couponRecord
      }, res => {
        resolve()
      })
    })
  },
  canObtain(coupon, user) {
    const result = {
      errMsg: null,
      success: false
    }
    // 判断可用条件
    if (coupon.onlyVip) {
      if (!user.vip) {
        result.errMsg = '仅VIP可用'
        return result
      }
    }
    if (coupon.start && coupon.end) {
      const curTime = new Date().getTime()
      if (curTime < coupon.start || curTime > coupon.end) {
        result.errMsg = '不在有效期内'
        return result
      }
    }
    if (coupon.left && !(Number(coupon.left) > 0)) {
      result.errMsg = '已抢光'
      return result
    }

    if (coupon.userId && coupon.userId != user._id) {
      result.errMsg = '当前用户不可用'
      return result
    }
    if (coupon.limit) {
      if (user.couponRecord?.[coupon._id].num * 1 >= coupon.limit) {
        result.errMsg = '已达到限领量'
        return result
      }
    }
    if (coupon.openGId) {
      if (user.couponRecord?.[coupon._id]?.openGId == coupon.openGId) {
        result.errMsg = '已领过该券'
        return result
      }
    }

    return {
      success: true
    }
  },
  deleteCoupon(id, cb) {
    ui.confirmx('是否删除？')
      .then(res => {
        if (!res) return
        ui.loading()
        ds.cloudRemove('coupons', {
          _id: id
        }, res => {
          const success = res.result.errMsg.endsWith(":ok")
          ui.loading(false)
          if (!success) ui.toast(false, res)
          else ui.toast(success, '', res => {
            if (cb) cb()
          })
        })
      })
      .catch(err => {
        ui.loading(false)
        ui.toast(false, err)
        console.error(err)
      })
  },
  isCouponValid(order) {
    let minUnit = -1
    const snap = order.goodsSnap ?? []
    snap.forEach(goods => {
      (goods.couponList || []).forEach(c => {
        minUnit = (minUnit < 0 ? c.unit * 1 : Math.min(minUnit, c.unit * 1))
      })
    })
    const leftPoints = (typeof order.coupon?.leftPoints != 'undefined' ? order.coupon.leftPoints : order.totalFee) * 1

    // console.log(order, minUnit, leftPoints)
    return order.status == '已送达' && order.payStatus == 'success' && minUnit > 0 && minUnit < leftPoints
  },
  setupDuration(coupon) {
    if (coupon.duration == 'days' && coupon.days) {
      const now = Date.now()
      coupon.start = now
      coupon.end = dateTool.dayEnd(now + coupon.days * 24 * 60 * 60 * 1000)
    }
    return coupon
  }
}